package j.framework.tags.form;

import j.framework.core.ObjectUtils;
import j.framework.core.entity.Entity;
import j.framework.core.entity.EntityProperty;
import j.util.DES;
import j.util.StringUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.util.Map;

/**
 * User: jason
 * Date: 2014/12/16 16:11
 */
public class FormTag extends BodyTagSupport {

    private FormTagWriter writer;

    public FormTagWriter getWriter() {
        return writer;
    }

    @Override
    public int doStartTag() throws JspException {
        writer = new FormTagWriter(this.pageContext.getOut());
        writer.beginTag("form");
        writer.writeFormTagProperty("id", formId);
        if(StringUtils.isNotEmpty(this.action)){
            String action = this.action;
            if(!action.startsWith("/")){
                //不是以"/"开头，则加上MemberStatus.LOGIN_FILTER_NAME
                action = "/user/"+action;
            }
            writer.writeFormTagProperty("action", action);
        }else{
            writer.writeFormTagProperty("action","/user/req");
        }
        if(StringUtils.isNotEmpty(method)){
            if(method.equalsIgnoreCase("get") || method.equalsIgnoreCase("post")){
                writer.writeFormTagProperty("method", method);
            }
        }else{
            //默认为post
            writer.writeFormTagProperty("method", "post");
        }
        if(StringUtils.isNotEmpty(target)){
            writer.writeFormTagProperty("target", target);
        }
        if(StringUtils.isNotEmpty(autocomplete)){
            writer.writeFormTagProperty("autocomplete", autocomplete);
        }else{
            //默认为off
            writer.writeFormTagProperty("autocomplete", "off");
        }
        writer.writeFormTagProperty("onsubmit", onsubmit);
        writer.endTag();
        //这里加入关于web请求的一些必须的参数
        if(StringUtils.isNullOrEmpty(target) || target.equalsIgnoreCase("post_form")){
            if(this instanceof j.framework.tags.easyui.FormTag){
                //通过easyui ajax提交
                writer.writeSomething("<input type=\"hidden\" name=\"HTTP_POST_BY_FORM\" value=\"2\"/>");
            }else{
                //通过iframe提交
                writer.writeSomething("<input type=\"hidden\" name=\"HTTP_POST_BY_FORM\" value=\"1\"/>");
            }
        }
        if(StringUtils.isNotEmpty(entityId)){
            //这是提交实体的增加或修改
            writer.writeSomething("<input type=\"hidden\" name=\"eid\" value=\""+ DES.encrypt(entityId)+"\"/>");
            String entityAction = (String)this.pageContext.getRequest().getAttribute("action");
            if(StringUtils.isNotEmpty(entityAction)){
                writer.writeSomething("<input type=\"hidden\" name=\"act\" value=\""+entityAction+"\"/>");
                if(entityAction.equals("u")){
                    //这是修改
                    Entity e = (Entity)this.pageContext.getRequest().getAttribute("e");
                    String value;
                    EntityProperty p;
                    for(String key : e.primaryKeys){
                        p = e.properties.get(key);
                        value = (String)getFormDataValue(key);
                        if(StringUtils.isNullOrEmpty(p.getSequenceKey()) &&
                                StringUtils.isNullOrEmpty(value)){
                            //没有指定序列，这是需要在页面上指定主键的，这是在显示新增表单的
                            continue;
                        }
                        if(StringUtils.isNullOrEmpty(value)){
                            throw new JspException("没有指定主键["+p.getLabelName()+"]值，不能完成修改操作！");
                        }
                        writer.writeSomething(String.format("<input type=\"hidden\" name=\"%s\" value=\"%s\"/>",
                                key,value));
                    }
                }
            }
        }
        if((StringUtils.isNullOrEmpty(action) || action.equalsIgnoreCase("/user/req"))
                && StringUtils.isNotEmpty(requestId)) {
            writer.writeSomething("<input type=\"hidden\" name=\"action\" value=\"save\"/>");
            writer.writeSomething("<input type=\"hidden\" name=\"rid\" value=\""+ DES.encrypt(requestId)+"\"/>");
        }
        return EVAL_BODY_INCLUDE;
    }

    @Override
    public int doAfterBody() throws JspException {
        return SKIP_BODY;
    }

    @Override
    public int doEndTag() throws JspException {
        writer.closeTag("form");
        if(!(this instanceof j.framework.tags.easyui.FormTag)){
            writer.writeSomething("<iframe width=\"0\" scrolling=\"no\" height=\"0\" frameborder=\"0\" name=\"post_form\" src=\"/none.html\" style=\"display:none;\"></iframe>");
        }
        writer.writeSomething("<script>var formId='"+formId+"';</script>");
        writer.flush();
        writer = null;
        return EVAL_PAGE;
    }

    public Object getFormDataValue(String key){
        if(null==formDataMap){
            return null;
        }
        return formDataMap.get(key);
    }

    private String formId;
    protected String action;
    protected String entityId;
    private String method;
    private String requestId;
    private String target;
    private String autocomplete;
    private String onsubmit;
    private Object formData;
    private Map<String,Object> formDataMap;

    public Object getFormData() {
        return formData;
    }

    public void setFormId(String formId) {
        this.formId = formId;
    }
    protected String getFormId(){
        return this.formId;
    }

    public void setAction(String action) {
        this.action = action;
    }
    protected String getAction(){
        if(StringUtils.isNotEmpty(action)){
            if(action.startsWith("/")){
                return action;
            }
            return String.format("%s/%s","/user",action);
        }else{
            return String.format("%s/req", "/user");
        }
    }

    public void setEntityId(String entityId) {
        this.entityId = entityId;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public void setTarget(String target) {
        this.target = target;
    }

    public void setAutocomplete(String autocomplete) {
        this.autocomplete = autocomplete;
    }

    public void setOnsubmit(String onsubmit) {
        this.onsubmit = onsubmit;
    }
    protected String getOnSubmit(){
        return onsubmit;
    }

    public void setFormData(Object formData) {
        this.formData = formData;
        if(null!=formData){
            formDataMap = ObjectUtils.toMap(formData);
        }else if(formDataMap!=null){
            formDataMap.clear();
            formDataMap = null;
        }
    }
}
